package com.hxzy.filter;

import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.web.resp.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("Authorization");

        boolean isPassed = Objects.nonNull(authorization) &&   authorization.contains("abcd");


        if(!isPassed){
           return unauthorizedResponse(exchange);

        }

        return chain.filter(exchange);

    }


    //设置webflux模型响应
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange)
    {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json");

        R<Object> build = R.build(AckCode.TOKEN_FAIL);

        String jsonStr= JSONUtil.toJsonStr(build);

        //响应式模型需要的数据对象
        DataBuffer dataBuffer = response.bufferFactory().wrap( jsonStr.getBytes());

        return response.writeWith(Mono.just(dataBuffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
